package com.lizhi.note.controller;

import com.lizhi.note.payload.ApiResponse;
import com.lizhi.note.payload.ResponseUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@RestController
@RequestMapping("/api/image")
public class ImageController {
    @PostMapping(("/upload/{notepageId}"))
    public ResponseEntity<ApiResponse> uploadImage(@PathVariable Long notepageId, @RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            return ResponseUtil.error(HttpStatus.BAD_REQUEST.value(), "请选择要上传的图片");
        }
        //System.out.println("99999999999: " + System.getProperty("user.dir"));
        // 确保上传目录存在
        Path uploadPath = Paths.get("./data/static/api/img/" + notepageId);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }

        // 生成唯一文件名，避免冲突
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String uniqueFilename = UUID.randomUUID().toString() + fileExtension;

        // 保存文件
        Path filePath = uploadPath.resolve(uniqueFilename);
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

        // 返回访问URL（假设前端通过该URL访问图片）
        String imageUrl = "/api/img/" + notepageId + "/" + uniqueFilename;
        return ResponseUtil.success(imageUrl);
    }
}
